<!--------------------------------
 - @Author: Your Name
 - @LastEditor: Your Name
 - @LastEditTime: 2025-11-07
 - Copyright © 2025 Your Name
 --------------------------------->

<template>
  <CommonPage>
    <template #action>
      <NButton v-permission="'AddOauthConfig'" type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        添加OAuth配置
      </NButton>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1400"
      :columns="columns"
      :get-data="api.read"
    >
      <MeQueryItem label="提供商" :label-width="70">
        <n-input
          v-model:value="queryItems.provider"
          type="text"
          placeholder="请输入提供商名称"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="状态" :label-width="70">
        <n-select
          v-model:value="queryItems.enabled"
          :options="[
            { label: '启用', value: true },
            { label: '禁用', value: false },
          ]"
          clearable
          placeholder="请选择状态"
        />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="modalRef" width="800px">
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="120"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="配置名称"
          path="name"
          :rule="{
            required: true,
            message: '请输入配置名称',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.name" placeholder="请输入配置名称" />
        </n-form-item>

        <n-form-item
          label="提供商"
          path="provider"
          :rule="{
            required: true,
            message: '请选择提供商',
            trigger: ['change'],
          }"
        >
          <n-select
            v-model:value="modalForm.provider"
            :options="providerOptions"
            label-field="name"
            value-field="value"
            placeholder="请选择提供商"
            filterable
          />
        </n-form-item>

        <n-form-item
          label="配置类型"
          path="configType"
          :rule="{
            required: true,
            message: '请选择配置类型',
            trigger: ['change'],
          }"
        >
          <n-select
            v-model:value="modalForm.configType"
            :options="configTypeOptions"
            label-field="name"
            value-field="value"
            placeholder="请选择配置类型"
          />
        </n-form-item>

        <n-form-item label="客户端ID" path="clientId">
          <n-input
            v-model:value="modalForm.clientId"
            type="password"
            show-password-on="mousedown"
            placeholder="请输入客户端ID"
          />
        </n-form-item>

        <n-form-item label="客户端密钥" path="clientSecret">
          <n-input
            v-model:value="modalForm.clientSecret"
            type="password"
            show-password-on="mousedown"
            placeholder="请输入客户端密钥"
          />
        </n-form-item>

        <n-form-item label="回调地址" path="redirectUri">
          <n-input
            v-model:value="modalForm.redirectUri"
            type="text"
            placeholder="请输入回调地址"
          />
        </n-form-item>

        <n-form-item label="授权范围" path="scopes">
          <n-input
            v-model:value="modalForm.scopes"
            type="text"
            placeholder="请输入授权范围，多个用逗号分隔"
          />
        </n-form-item>

        <n-form-item label="授权URL" path="authUrl">
          <n-input
            v-model:value="modalForm.authUrl"
            type="text"
            placeholder="请输入获取授权码的URL"
          />
        </n-form-item>

        <n-form-item label="令牌URL" path="tokenUrl">
          <n-input
            v-model:value="modalForm.tokenUrl"
            type="text"
            placeholder="请输入获取访问令牌的URL"
          />
        </n-form-item>

        <n-form-item label="用户信息URL" path="userInfoUrl">
          <n-input
            v-model:value="modalForm.userInfoUrl"
            type="text"
            placeholder="请输入获取用户信息的URL"
          />
        </n-form-item>

        <n-form-item label="用户信息请求方法" path="userInfoMethod">
          <n-select
            v-model:value="modalForm.userInfoMethod"
            :options="[
              { label: 'GET', value: 'GET' },
              { label: 'POST', value: 'POST' },
            ]"
            placeholder="请选择获取用户信息的请求方法"
          />
        </n-form-item>

        <n-form-item label="登录图标" path="icon">
          <n-input
            v-model:value="modalForm.icon"
            type="text"
            placeholder="请输入图标的CSS类名，如：i-simple-icons:github"
          />
        </n-form-item>

        <n-form-item label="排序" path="sortOrder">
          <n-input-number
            v-model:value="modalForm.sortOrder"
            placeholder="请输入排序值"
            :min="0"
          />
        </n-form-item>

        <n-form-item label="是否启用" path="enabled">
          <NSwitch v-model:value="modalForm.enabled">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              禁用
            </template>
          </NSwitch>
        </n-form-item>

        <n-form-item
          v-if="modalForm.configType === 'CUSTOM'"
          label="自定义配置"
          path="customConfig"
        >
          <n-input
            v-model:value="modalForm.customConfig"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入自定义配置JSON"
          />
        </n-form-item>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { NButton, NSwitch, NTag } from 'naive-ui'
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import { formatDateTime } from '@/utils'
import api from './api'

defineOptions({ name: 'OauthConfigMgt' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

// 提供商选项
const providerOptions = ref([])
api.getProviderOptions().then(({ data = [] }) => (providerOptions.value = data))

// 配置类型选项
const configTypeOptions = ref([])
api.getConfigTypeOptions().then(({ data = [] }) => (configTypeOptions.value = data))

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleDelete,
  handleOpen,
  handleSave,
} = useCrud({
  name: 'OAuth配置',
  initForm: {
    enabled: true,
    userInfoMethod: 'GET',
    configType: 'SYSTEM_BUILTIN',
    sortOrder: 0,
  },
  doCreate: api.create,
  doDelete: api.delete,
  doUpdate: api.update,
  refresh: () => $table.value?.handleSearch(),
})

const columns = [
  { title: '配置名称', key: 'name', width: 150, ellipsis: { tooltip: true } },
  {
    title: '提供商',
    key: 'provider',
    width: 120,
    render: (row) => {
      const provider = providerOptions.value.find(item => item.value === row.provider)
      return provider ? h(NTag, { type: 'info' }, { default: () => provider.name }) : row.provider
    },
  },
  {
    title: '配置类型',
    key: 'configType',
    width: 120,
    render: (row) => {
      const type = configTypeOptions.value.find(item => item.value === row.configType)
      return type ? h(NTag, { type: 'success' }, { default: () => type.name }) : row.configType
    },
  },
  {
    title: '回调地址',
    key: 'redirectUri',
    width: 200,
    ellipsis: { tooltip: true },
  },
  {
    title: '授权范围',
    key: 'scopes',
    width: 150,
    ellipsis: { tooltip: true },
  },
  {
    title: '排序',
    key: 'sortOrder',
    width: 80,
    render: row => h('span', row.sortOrder || 0),
  },
  {
    title: '状态',
    key: 'enabled',
    width: 100,
    render: row =>
      h(
        NSwitch,
        {
          size: 'small',
          rubberBand: false,
          value: row.enabled,
          loading: !!row.enableLoading,
          onUpdateValue: () => handleEnable(row),
        },
        {
          checked: () => '启用',
          unchecked: () => '禁用',
        },
      ),
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: 180,
    render(row) {
      return h('span', formatDateTime(new Date(row.createdAt)))
    },
  },
  {
    title: '更新时间',
    key: 'updatedAt',
    width: 180,
    render(row) {
      return h('span', formatDateTime(new Date(row.updatedAt)))
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 350,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleTest(row),
          },
          {
            default: () => '测试',
            icon: () => h('i', { class: 'i-carbon:test-tube text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleView(row),
          },
          {
            default: () => '查看',
            icon: () => h('i', { class: 'i-carbon:document-view text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            class: 'ml-12px',
            onClick: () => handleEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-material-symbols:edit-outline text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

async function handleEnable(row) {
  row.enableLoading = true
  try {
    await api.update({ id: row.id, enabled: !row.enabled })
    row.enableLoading = false
    $message.success('操作成功')
    $table.value?.handleSearch()
  }
  catch (error) {
    console.error(error)
    row.enableLoading = false
  }
}

function handleView(row) {
  handleOpen({ action: 'view', title: '查看OAuth配置', row })
}

function handleEdit(row) {
  handleOpen({ action: 'edit', title: '编辑OAuth配置', row })
}

async function handleTest(row) {
  try {
    const result = await api.testConfig(row.id)
    $message.success(`测试成功: ${result.data.message}`)
    console.log('测试结果:', result.data)
  }
  catch (error) {
    $message.error(`测试失败: ${error.message}`)
    console.error('测试失败:', error)
  }
}
</script>
